package com.bjb.vr.common.aop;

import com.bjb.vr.common.annotation.InvalidateCache;
import com.bjb.vr.common.constant.CacheConstant;
import com.bjb.vr.common.utils.GuavaCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.lang.reflect.Field;

/**
 * 缓存操作切面
 *
 * @version 1.0.0
 * @author: HuJingBo
 * @time: 2022/3/25 15:04
 */
@Component
@Aspect
@Slf4j
public class CacheAspect {

    @Pointcut("@annotation(com.bjb.vr.common.annotation.InvalidateCache)")
    private void cachePointcut() {
    }

    /**
     * 执行环绕切面方法
     *
     * @param pjp
     * @param invalidateCache
     * @return
     * @throws Throwable
     */
    @Around(value = "cachePointcut() && @annotation(invalidateCache)")
    public Object advice(ProceedingJoinPoint pjp, InvalidateCache invalidateCache) throws Throwable {
        // 获取注解参数并校验
        Assert.isTrue(StringUtils.isNotBlank(invalidateCache.cacheName()), "删除缓存的Name不能为空,缓存删除失败");
        Field field = GuavaCacheUtil.class.getDeclaredField(invalidateCache.cacheName());
        Assert.notNull(field, "未找到该缓存配置......");

        // 执行删除缓存操作--字典表；其他缓存需要自行添加
        if (invalidateCache.cacheName().equals(CacheConstant.DICTIONARY)) {
            GuavaCacheUtil.getDictionaryCache().invalidateAll();
        }
        return pjp.proceed();
    }
}
